package q3;

import java.util.Random;

import genetic.Genotype;
import genetic.Phenotype;

public class cliquePhenotype extends Phenotype {

	private int _size;
	private ReadFile _rf;
	public cliquePhenotype(){
		
	}

	public cliquePhenotype(int size, ReadFile rf){
		_size = size;
		_rf = rf;
	}
	
	@Override
	public Genotype createRandomInstance() {
		Genotype ins = new cliqueGenotype(_size, _rf.max);
		return ins;
	}

	@Override
	public Genotype[] crossover(Genotype g1, Genotype g2) {
		Random r = new Random();
		int spot = r.nextInt(_size);
		cliqueGenotype g3 = (cliqueGenotype)g1.clone();
		cliqueGenotype g4 = (cliqueGenotype)g2.clone();
		for(int i = spot; i <_size; i++){
			boolean tmp = g3.instance[i];
			g3.instance[i] = g4.instance[i];
			g4.instance[i] = tmp;
		}
		Genotype[] ans = new Genotype[2];
		ans[0]=g3;
		ans[1]=g4;
		return ans;
	}

	@Override
	public double fitness(Genotype g) {
		int counter=0;
		for(int i = 0; i <_size; i++){
			if(((cliqueGenotype)g).instance[i]==true)
				counter++;
		}
		int wrong=0;
		for(int i = 0; i <_size-1; i++){
			if(((cliqueGenotype)g).instance[i]==true){
				for(int j = i+1; j <_size; j++){
					if(((cliqueGenotype)g).instance[j]==true){
						if(_rf.matrix[i][j]!=true){
							wrong++;
						}
					}
				}
			}
		}
		//wrong = wrong*100;
		//base = base - wrong;
		int base = 550; //(counter*(counter-1))/2;
		if(wrong==0 && (counter > 1)){
			base = base - Math.min(550, (counter*counter));
		}
		return (double)(551 - base);
	}

	@Override
	public Genotype mutate(Genotype g, double Pm) {
		Random r = new Random();
		for(int i = 0; i <_size; i++){
			double m = r.nextDouble();
			if(m<=Pm)
				((cliqueGenotype)g).instance[i] = !((cliqueGenotype)g).instance[i];
		}
		return g;
	}

}
